"""Add a HashiCorp Vault server to the mix."""
import contextlib
import os
import typing
from unittest import mock

from . import cluster
from .. import misc
from ..logger import get_logger

LOGGER = get_logger(__name__)


class HashiCorpVaultServer(cluster.KubernetesCluster):
    """Add a HashiCorp Vault server to the mix."""

    @classmethod
    def setUpClass(cls) -> None:
        """Set up the service."""
        super().setUpClass()
        cls.enterClassContext(cls._vault())

    @classmethod
    @contextlib.contextmanager
    def _vault(cls) -> typing.Iterator[None]:
        service_id = 'vault'
        now = misc.now_tz_utc()
        with cls.k8s_namespace(service_id):
            LOGGER.info('Starting HashiCorp Vault')
            cls.k8s_deployment(namespace=service_id, name=service_id, setup_at=now, container={
                'image': 'docker.io/hashicorp/vault:latest',
                'startupProbe': cls.k8s_startup_probe(8200),
                'env': [
                    {'name': 'VAULT_DEV_ROOT_TOKEN_ID', 'value': 'root_token_id'},
                ],
            })
            cls.k8s_service(namespace=service_id, name=service_id)
            if not cls.k8s_wait(namespace=service_id, name=service_id, setup_at=now):
                raise Exception(f'{service_id} did not start up')

            with mock.patch.dict(os.environ, {
                'VAULT_ADDR': f'http://{cls.hostname}:8200',
                'VAULT_TOKEN': 'root_token_id',
                'VAULT_MOUNT_POINT': 'secret',
            }):
                yield
